﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace _13_Task_线程取消
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //创建一个CancellationTokenSource对象，用于取消任务
            CancellationTokenSource cts = new CancellationTokenSource();
            //获取CancellationToken令牌对象
            CancellationToken token = cts.Token;

            //创建一个Task对象，用于执行任务
            Task task1 = new Task(() => DoWrok(token), token);
            Task task2 = new Task(() => DoWrok(token), token);
            Task task3 = new Task(() => DoWrok(token), token);

            //启动任务
            task1.Start();
            task2.Start();
            task3.Start();

            Console.WriteLine("按任意键取消任务");
            Console.Read();

            //取消任务
            cts.Cancel();

            try
            {
                //阻塞当前线程，等待task线程执行完毕
                task1.Wait();
                task2.Wait();
                task3.Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[{DateTime.Now}] [Main] Task线程异常:{ex.Message}");
            }

            Console.ReadKey();
        }


        public static void DoWrok(CancellationToken token)
        {
            try
            {
                for (int i = 0; i < 100; i++)
                {
                    if (token.IsCancellationRequested)//判断是否接受到了线程停止的通知
                    {
                        Console.WriteLine($"[{DateTime.Now}] [DoWrok] Task线程取消");
                        token.ThrowIfCancellationRequested();//抛出OperationCanceledException异常
                    }
                    Console.WriteLine($"[{DateTime.Now}] [DoWrok] Task线程执行中...{i}");
                    Thread.Sleep(1000);
                }
                Console.WriteLine($"[{DateTime.Now}] [DoWrok] Task线程执行完成");
            }
            catch (Exception ex)
            {
                 Console.WriteLine($"[{DateTime.Now}] [DoWrok] Task线程异常:{ ex.Message}"); 
            }
        }

    }
}
